import { createSingle, fetchTransformStream } from "./utils";

const response = (ctx: ContextProps, callback: Function) => {
  if (ctx.delay) {
    console.log(`延时${ctx.delay}返回数据`);
    setTimeout(() => {
      callback(new Response(ctx.resBody, ctx.response));
    }, ctx.delay);
  } else {
    callback(new Response(ctx.resBody, ctx.response));
  }
};

const createFetchHook = ({ onRequest, onResponse }) => {
  console.log("重现啊啊 ");
  const _fetch = window.fetch;
  (window as any).__fetch = _fetch;
  window.fetch = function (
    input: string | URL | globalThis.Request,
    init: RequestInit = {}
  ) {
    if (onRequest) {
      let ctx: ContextProps = {
        method: init.method || "get",
        data: init.body,

        url: input,
        resource: "fetch",
        headers: {
          ...init.headers,
        },
        setHeader: function (key: string, value: string) {
          if (!ctx.headers) {
            ctx.headers = {};
          }
          if (value) {
            ctx.headers[key] = value;
          } else {
            delete ctx.headers[key];
          }
          console.log("设置header", key, value);
        },
        resBody: init.body,
      };
      return new Promise((resolve) => {
        onRequest(ctx, {
          send(resBody: ResBodyType) {
            ctx.resBody = resBody;
            ctx.response = {
              headers: undefined,
              status: 200,
              statusText: "OK",
            };
            response(ctx, resolve);
          },
          next: (ctx: ContextProps) => {
            _fetch(ctx.url, {
              ...init,
              method: ctx.method,
              body: ctx.data,
              headers: ctx.headers,
            })
              // .then((res) => {
              //   res.headers
              //   return res.text();
              // })
              .then(async (res) => {
                console.log("res.headers", res.headers.get("Content-Type"));
                if (
                  res.headers.get("Content-Type").includes("text/event-stream")
                ) {
                  // 转换
                  // fetchTransformStream(res,resolve)
                  resolve(
                    new Response(res.body, {
                      headers: res.headers,
                      status: res.status,
                      statusText: res.statusText,
                    })
                  );
                } else {
                  const text = await res.text();
                  ctx.resBody = text;
                  ctx.response = {
                    status: res.status || 200,
                    statusText: res.statusText,
                    headers: res.headers,
                  };

                  if (onResponse) {
                    onResponse(ctx, {
                      send(resBody: ResBodyType) {
                        ctx.resBody = resBody;
                        response(ctx, resolve);
                      },
                      next(ctx) {
                        response(ctx, resolve);
                        // resolve(
                        //   new Response(ctx.resBody, {

                        //   })
                        // );
                      },
                    });
                  } else {
                    response(ctx, resolve);
                    // resolve(new Response(ctx.resBody));
                  }
                }
              });
          },
        });
      });
    }
    return _fetch.apply(this, arguments);
  };
};
export default createFetchHook;
